<extend name="Public/base"/>
<block name="style">
    <link rel="stylesheet" href="__STATIC__/styles/video_view.css">
    <link rel="stylesheet" href="__STATIC__/styles/vendors/video.min.css">
    <link rel="stylesheet" href="__STATIC__/styles/vendors/bootstrap-table.css">
    <link rel="stylesheet" href="__STATIC__/styles/vendors/bootstrap-select.min.css">
</block>
<block name="content">
    <div id="toolbar">
        <button id="remove" class="btn btn-danger btn-flat" disabled>
            <i class="glyphicon glyphicon-remove"></i>删除
        </button>
        <!--<select class="selectpicker">-->
        <!--<option>所有回传人</option>-->
        <!--</select>-->
        <select id ='searchOption' class="selectpicker right">
            <option value="1">部门</option>
            <option value="2">回传人</option>
        </select>
    </div>
    <table id="table" data-toolbar="#toolbar">
    </table>
    <div class="modal fade" id="confirm_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">确认</h4>
                </div>
                <div class="modal-body">
                    确定要删除吗?
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger btn-flat confirmDel">删除</button>
                    <button type="button" class="btn btn-default btn-flat" data-dismiss="modal">取消</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="video-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <button id="commBtn" type="button" class="btn-primary btn-flat pull-right">与其通信</button>
                    <button id="settingBtn" type="button" class="btn-primary btn-flat pull-right">设置</button>
                    <h4 class="modal-title">播放视频</h4>

                </div>
                <div class="modal-body">
                    <video id="my-video" class="video-js" controls preload="auto" width="768" height="561"
                           poster="//vjs.zencdn.net/v/oceans.png" data-setup="{}">

                        <p class="vjs-no-js">
                            查看视频请开启Javascript, 需要升级到
                            <a href="http://videojs.com/html5-video-support/" target="_blank">支持HTML5 视频</a>
                            的浏览器
                        </p>
                    </video>
                    <!--<div id="publisher"></div>-->
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="setting-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">推流设置</h4>

                </div>
                <div class="modal-body">
                    <div class="m-input">
                        <span class="u-input-name">摄像头：</span>
                        <select class="u-input" id="cameraSelect">
                        </select>
                    </div>
                    <div class="m-input">
                        <span class="u-input-name">麦克风：</span>
                        <select class="u-input" id="microPhoneSelect">
                        </select>
                    </div>
                    <div class="m-input">
                        <span class="u-input-name">清晰度：</span>
                        <select class="u-input" id="qualitySelect">
                            <option value="0">流畅（480*360@20）</option>
                            <option value="1">标清（640*480@20）</option>
                            <option value="2">高清（960*540@20）</option>
                        </select>
                    </div>
                    <div class="m-input">
                        <span class="u-input-name">推流地址：</span>
                        <input class="u-input" type="text" id="publishUrl">
                    </div>
                    <div class="m-input">
                        <button class="button button-primary button-rounded testBtn" id="previewBtn" onclick="startPreview()">预览</button>
                        <button class="button button-primary button-rounded testBtn" id="publishBtn" onclick="startPublish()">开始直播</button>
                        <span class="u-status"></span>
                    </div>
                    <div id="my-publisher"></div>
                </div>
            </div>
        </div>
    </div>

</block>

<block name="script">
    <script src="__STATIC__/scripts/vendors/bootstrap-select.min.js"></script>
    <script src="__STATIC__/scripts/vendors/bootstrap-table.js"></script>
    <script src="__STATIC__/scripts/vendors/video.min.js"></script>
    <script src="__STATIC__/scripts/vendors/videojs.ie8.min.js"></script>
    <script src="__STATIC__/scripts/vendors/sortable-jquery.binding.js"></script>
    <script src="__STATIC__/scripts/vendors/Sortable.min.js"></script>
    <script src="__STATIC__/scripts/vendors/videojs-contrib-hls.min.js"></script>
    <script src="//nos.netease.com/vod163/nePublisher.min.js"></script>
    <!--<script src="https://cdnjs.cloudflare.com/ajax/libs/videojs-contrib-hls/4.0.2/videojs-contrib-hls.min.js"></script>-->
    <script>


        var $table = $('#table');
        var $remove = $('#remove');
        var $videoModal = $('#video-modal');
        var $settingModal = $('#setting-modal');
        var tableHelper;
//        var $my_video;
        var $my_video = videojs('my-video');
        var $confirmModal = $('#confirm_modal');
        var $confirmDel = $('.confirmDel');
        var $commBtn = $('#commBtn');
        var $settingBtn = $('#settingBtn');
        var commStatus = 0;
        var liveName;
        var videoURL;
        var chat_key_pre = "{:C('IM_CHAT_KEY')}";
        var other_chat_id;
        var other_user_id;

        var cameraList, microPhoneList, cameraOptions = '', microPhoneOptions = '';
        var publishBtn = document.getElementById('publishBtn');
        var previewBtn = document.getElementById('previewBtn')
        var testInput = document.getElementsByClassName('u-input');
        var myPublisher = new nePublisher('my-publisher', {
            //viewOptions
            videoWidth: 960,
            videoHeight: 540,
            fps: 20,
            bitrate: 1500
        }, {
            //flashOptions
            previewWindowWidth: 862,
            previewWindowHeight: 486,
            wmode: 'transparent',
            quality: 'high',
            allowScriptAccess: 'always'
        }, function() {
            cameraList = this.getCameraList();
            microPhoneList = this.getMicroPhoneList();
            console.log(cameraList, microPhoneList);
            for (var i = cameraList.length - 1; i >= 0; i--) {
                cameraOptions = '<option value="' + i + '">' + cameraList[i] + '</option>' + cameraOptions;
            }
            for (var i = microPhoneList.length - 1; i >= 0; i--) {
                microPhoneOptions = '<option value="' + i + '">' + microPhoneList[i] + '</option>' + microPhoneOptions;
            }
            document.getElementById("cameraSelect").innerHTML = cameraOptions;
            document.getElementById("microPhoneSelect").innerHTML = microPhoneOptions;
        }, function(code, desc) {
            console.log(code, desc);
        });
        var qualityList = [
            {
                //流畅
                fps: 20,
                bitrate: 600,
                videoWidth:480,
                videoHeight:360
            },
            {
                //标清
                fps: 20,
                bitrate: 800,
                videoWidth:640,
                videoHeight:480
            },
            {
                //高清
                fps: 20,
                bitrate: 1500,
                videoWidth:960,
                videoHeight:540
            }
        ];
        var getCameraIndex = function() {
            var cameraSelect = document.getElementById("cameraSelect");
            var cameraIndex = cameraSelect.selectedIndex;
            return cameraSelect.options[cameraIndex].value;
        };
        var getMicroPhoneIndex = function() {
            var microPhoneSelect = document.getElementById("microPhoneSelect");
            var microPhoneIndex = microPhoneSelect.selectedIndex;
            return microPhoneSelect.options[microPhoneIndex].value;
        };
        var getQualityOption = function() {
            var qualitySelect = document.getElementById("qualitySelect");
            var qualityIndex = qualitySelect.selectedIndex;
            return qualityList[qualityIndex];
        };
        var startPreview = function() {
            myPublisher.startPreview(getCameraIndex());
            document.getElementsByClassName('u-status')[0].innerHTML = '预览中';
        };
        var startPublish = function() {
            var publishUrl = document.getElementById("publishUrl").value;
            startPublishCall();
            myPublisher.setCamera(getCameraIndex());
            myPublisher.setMicroPhone(getMicroPhoneIndex());
            myPublisher.startPublish(publishUrl, getQualityOption(),function(code, desc) {
                console.log(code, desc);
                alert(code + '：' + desc);
                stopPublishCall();
            });
        };
        var stopPublish = function() {
            myPublisher.stopPublish();
            stopPublishCall();
        };
        var startPublishCall = function() {
            console.log('推流开始');
            document.getElementsByClassName('u-status')[0].innerHTML = '直播中';
            publishBtn.innerHTML = '停止直播';
            publishBtn.onclick = stopPublish;
            for (var i = testInput.length - 1; i >= 0; i--) {
                testInput[i].disabled = true;
            }
            previewBtn.disabled = true;

        };
        var stopPublishCall = function() {
            console.log('推流结束');
            document.getElementsByClassName('u-status')[0].innerHTML = '预览中';
            publishBtn.innerHTML = '开始直播';
            publishBtn.onclick = startPublish;
            for (var i = testInput.length - 1; i >= 0; i--) {
                testInput[i].disabled = false;
            }
            previewBtn.disabled = false;
        };


        $videoModal.on('hide.bs.modal',function () {
            $my_video.width = 0;
            $my_video.height = 0;
        });

        var TableHelper = function(){
            var oTableHelper = new Object();

            oTableHelper.selections = [];

            oTableHelper.init = function(){
                $table.bootstrapTable({
                    formatLoadingMessage: function () {
                        return '正在努力地加载数据中，请稍候……';
                    },
                    formatRecordsPerPage: function (pageNumber) {
                        return '每页显示 ' + pageNumber + ' 条记录';
                    },
                    formatShowingRows: function (pageFrom, pageTo, totalRows) {
                        return '显示第 ' + pageFrom + ' 到第 ' + pageTo + ' 条记录，总共 ' + totalRows + ' 条记录';
                    },
                    formatSearch: function () {
                        return '搜索';
                    },
                    formatNoMatches: function () {
                        return '没有找到匹配的记录';
                    },
                    formatPaginationSwitch: function () {
                        return '隐藏/显示分页';
                    },
                    formatRefresh: function () {
                        return '刷新';
                    },
                    formatToggle: function () {
                        return '切换';
                    },
                    formatColumns: function () {
                        return '列';
                    },
                    responseHandler:function(res){
                        return res;
                    },
                    url:"{:U('realtimeList')}",
                    method:'get',
                    striped:true,
                    cache:false,
                    pagination:true,
                    sortable:false,
                    sortOrder:'asc',
                    sidePagination:'server',
                    queryParams:oTableHelper.queryParams,
                    pageNumber:1,
                    pageSize:10,
                    pageList:[10,20,50],
                    uniqueId:'real_time_id',
                    search:true,
                    height:getHeight(),

                    columns:[
                        {
                            checkbox:true,
                            align:'center'
                        },
                        {
                            field: 'video_url',
                            title: '视频',
                            align: 'center',
                            formatter: function (value) {
                                return '<a href="javascript: void 0" value="'+ "{:C('PRE_VIDEO_URL')}" +value+'" class="title glyphicon glyphicon-play-circle" aria-hidden="true"></a>';
                            },
                            events: operateEvents
                        },
                        {
                            field: 'user_name',
                            title: '回传人',
                            align: 'center',
                        },
                        {
                            field:'org_name',
                            title:'部门',
                            align:'center',
                        },
                        {
                            field: 'add_time',
                            title: '回传时间',
                            align: 'center'
                        },
                        {
                            field: 'position',
                            title: '地址',
                            align: 'center'
                        }
                    ]
                });


//                setTimeout(function () {
//                    $table.bootstrapTable('resetView');
//                }, 2000);

//                $(window).resize(function () {
//                    setTimeout(function () {
//                        $table.bootstrapTable('resetView', {
//                            height: getHeight()
//                        });
//                    }, 100);
//                });
                $(window).resize(function () {
                    $table.bootstrapTable('resetView', {height:getHeight()});
                });

                $table.on('check.bs.table uncheck.bs.table ' +
                        'check-all.bs.table uncheck-all.bs.table', function () {
                    $('#remove').prop('disabled', !$table.bootstrapTable('getSelections').length);

                    // save your data, here just save the current page
                    oTableHelper.selections = oTableHelper.getIdSelections();
                    // push or splice the selections if you want to save all data selections
                });





                $table.on('expand-row.bs.table', function (e, index, row, $detail) {
                    if (index % 2 == 1) {
                        $detail.html('Loading from ajax request...');
                        $.get('LICENSE', function (res) {
                            $detail.html(res.replace(/\n/g, '<br>'));
                        });
                    }
                });


            };

            oTableHelper.queryParams = function(params){
                var temp = {
                    limit:params.limit,
                    offset:params.offset,
                    search:params.search,
                    searchOption:$("#searchOption").val()
                };
                return temp;
            };

            oTableHelper.getIdSelections = function(){
                return $.map($table.bootstrapTable('getSelections'), function (row) {
                    return row.real_time_id;
                })
            };

            oTableHelper.refresh = function(){
                $table.bootstrapTable('refresh');
            };

            return oTableHelper;
        }



        window.operateEvents = {
            'click .title': function (e, value, row, index) {
                $videoModal.modal('show');
//                $my_video.src("{:C('PRE_VIDEO_URL')}" + value);
//                $my_video.play();
//                $my_video.hls("{:C('PRE_VIDEO_URL')}" + value);

                other_user_id = row.user_id;
                other_chat_id = chat_key_pre + other_user_id;
//                $my_video = videojs('my-video', {}, function () {
//                    videojs.log('player is ready');
//                    this.src({
//                        src: value,
//                        type:'rtmp/mp4'
//                    });
//                });
                $my_video.src(
                    {
                        src: value,
                        type:'rtmp/mp4'
//                        withCredentials:true
                    }
                );
            },
        };

        function getHeight() {
            return $("#right").height() - 25 - $('#myTabs').outerHeight();
        }


        function initValidate(){
            var obj = $('#monitorForm');
            obj.validate({
                debug:true,
                submitHandler:function(form){
                    var url = $(form).prop('action')
                    var postData = $(form).serialize();

                    $.post(url, postData, function(data){
                        if(data.status == 1){
                            tableHelper.refreshMonitor();
                            $('#monitorForm')[0].reset();
                            $monitorModal.modal('hide');
                        }else{
                            layer.msg(data.msg);
                        }

                    });
                },
                rules:{
                    video_url:'required',
                    title:'required'
                },
                messages:{
                    video_url:"RTSP地址不能为空",
                    title:'备注不能为空'
                }
            })
        }


        $(function () {

            tableHelper = new TableHelper();
            tableHelper.init();


            $remove.click(function () {
                $confirmModal.modal('show');
            });

            $videoModal.on('hide.bs.modal', function () {
               $my_video.reset();
            });


            $confirmDel.click(function(){
                $confirmModal.modal('hide');

                    $.post({
                        url:"{:U('delete')}",
                        data:{
                            selectedIds : tableHelper.selections
                        },
                        success:function(data){
                            if(data.status == 1){
                                layer.msg('删除成功');
                                tableHelper.refresh();
                            }else{
                                layer.msg(data.msg);
                            }
                        }
                    });

            });

            $settingBtn.click(function () {
                $settingModal.modal('show');
            });


            $commBtn.click(function () {
                //初始状态，建立通信
                if(commStatus == 0){
                    $.get(
                        "{:U('connect')}",
                        function (data) {
                            if (data.state == 1){
                                var pullUrl = data.pushUrl;
                                if(chatSocket && chatSocket.readyState == WebSocket.OPEN){
                                    var msg = new Object();
                                    msg.cmd = '2';
                                    msg.too = other_chat_id;
                                    msg.type = 1;
                                    msg.body = new Object();
                                    msg.body.msg = pullUrl;
                                    msg.body.type = 2;
                                    chatSocket.send(JSON.stringify(msg));
                                }else{
                                    layer.msg('socket连接断开，刷新页面以重试');
                                }
                                var item = data.data[0];
                                liveName = item.liveName;
                                videoURL = item.videoURL;
                                $('#publishUrl').val(videoURL);
                                startPublishCall();
                                myPublisher.setCamera(getCameraIndex());
                                myPublisher.setMicroPhone(getMicroPhoneIndex());
                                myPublisher.startPublish(videoURL, getQualityOption(), function (code, desc) {
                                    console.log(code, desc);
                                    alert(code + '：' + desc);
                                    stopPublishCall();
                                })
                            }
                        }
                    );
                }else if(commStatus == 2){
                    //建立通信成功后，断开连接
                    $.get(
                        "{:U('close')}",
                        function (data) {

                        }
                    )
                }

            });



            $(window).resize(function () {
                setTimeout(function () {
                    $table.bootstrapTable('resetView', {
                        height: getHeight()
                    });
                }, 100);
            });
            /**
             * 这是将视频设为可拖动排序的部分
             */
            $('#videos').sortable({
                //排序时动画during 150ms
                animation: 150,
                //只有在‘备注’的区域可以被拖动
                handle: '.addition'
            });


            $('.fixed-table-container').addClass('box box-primary');



            /**
             * 定制的播放/暂停按钮
             */
            $('.custom-control').click(function () {
                var $this = $(this);
                //通过data-value找到video的index
                var index = $this.attr('data-value');
                /**
                 * 重要，一个页面有多个视频时，若要手动控制视频，需要每个video有不同id
                 */
                var video_instance = videojs('video-' + index);
                //判断现在是播放还是暂停
                if($this.hasClass('glyphicon-pause')) {
                    $this.removeClass('glyphicon-pause');
                    $this.addClass('glyphicon-play');
                    video_instance.pause();
                } else {
                    $this.removeClass('glyphicon-play');
                    $this.addClass('glyphicon-pause');
                    video_instance.play();
                }
            });

        });


    </script>
</block>